package com.lei.baweiliao.view.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bumptech.glide.load.model.Model;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.lei.baweiliao.R;
import com.lei.baweiliao.adapter.InviteAdapter;
import com.lei.baweiliao.bean.InvationInfo;
import com.lei.baweiliao.bean.UserInfo;
import com.lei.baweiliao.threadhelper.ThreadHelper;
import com.lei.baweiliao.utils.Constants;

import java.util.ArrayList;
import java.util.List;

public class FriendActivity extends Activity {
    private ListView lv_invite;
    private final InviteAdapter.OnInviteListener mOnInviteListener = new InviteAdapter.OnInviteListener() {
        @Override
        public void onAccept(final InvationInfo invationInfo) {
            // 通知环信服务器，点击了接受按钮
            ThreadHelper.getInstance().getExecutors().execute(() -> {
                try {
                    Log.e("添加好友接口调用", invationInfo.getUser().getHxid());
                    EMClient.getInstance().contactManager().acceptInvitation(invationInfo.getUser().getHxid());

                    // 数据库更新
//                        Model.getInstance().getDbManager().getInviteTableDao().updateInvitationStatus(InvationInfo.InvitationStatus.INVITE_ACCEPT,invationInfo.getUser().getHxid());

                    runOnUiThread(() -> {
                        // 页面发生变化
                        Toast.makeText(FriendActivity.this, "接受了邀请", Toast.LENGTH_SHORT).show();

                        // 刷新页面
                        refresh();
                    });

                } catch (HyphenateException e) {
                    e.printStackTrace();

                    runOnUiThread(() -> Toast.makeText(FriendActivity.this, "接受邀请失败", Toast.LENGTH_SHORT).show());
                }
            });
        }

        @Override
        public void onReject(final InvationInfo invationInfo) {
            ThreadHelper.getInstance().getExecutors().execute(() -> {
                try {
                    EMClient.getInstance().contactManager().declineInvitation(invationInfo.getUser().getHxid());

                    // 数据库变化
//                        Model.getInstance().getDbManager().getInviteTableDao().removeInvitation(invationInfo.getUser().getHxid());

                    // 页面变化
                    runOnUiThread(() -> {
                        Toast.makeText(FriendActivity.this, "拒绝成功了", Toast.LENGTH_SHORT).show();

                        // 刷新页面
                        refresh();
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();

                    runOnUiThread(() -> Toast.makeText(FriendActivity.this, "拒绝失败了", Toast.LENGTH_SHORT).show());
                }
            });
        }

        // 接受邀请按钮
        @Override
        public void onInviteAccept(final InvationInfo invationInfo) {
            ThreadHelper.getInstance().getExecutors().execute(() -> {
                try {
                    // 告诉环信服务器接受了邀请
                    EMClient.getInstance().groupManager().acceptInvitation(invationInfo.getGroup().getGroupId(), invationInfo.getGroup().getInvatePerson());

                    // 本地数据更新
                    invationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_ACCEPT_INVITE);
//                        Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invationInfo);

                    // 内存数据的变化
                    runOnUiThread(() -> {
                        Toast.makeText(FriendActivity.this, "接受邀请", Toast.LENGTH_SHORT).show();

                        // 刷新页面
                        refresh();
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    runOnUiThread(() -> Toast.makeText(FriendActivity.this, "接受邀请失败", Toast.LENGTH_SHORT).show());
                }
            });
        }

        // 拒绝邀请按钮
        @Override
        public void onInviteReject(final InvationInfo invationInfo) {
            ThreadHelper.getInstance().getExecutors().execute(() -> {
                try {
                    // 告诉环信服务器拒绝了邀请
                    EMClient.getInstance().groupManager().declineInvitation(invationInfo.getGroup().getGroupId(), invationInfo.getGroup().getInvatePerson(), "拒绝邀请");

                    // 更新本地数据库
                    invationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_REJECT_INVITE);
//                        Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invationInfo);

                    // 更新内存的数据
                    runOnUiThread(() -> {
                        Toast.makeText(FriendActivity.this, "拒绝邀请", Toast.LENGTH_SHORT).show();

                        // 刷新页面
                        refresh();
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            });
        }

        // 接受申请按钮
        @Override
        public void onApplicationAccept(final InvationInfo invationInfo) {
            ThreadHelper.getInstance().getExecutors().execute(() -> {
                try {
                    // 告诉环信服务器接受了申请
                    EMClient.getInstance().groupManager().acceptApplication(invationInfo.getGroup().getGroupId(), invationInfo.getGroup().getInvatePerson());

                    // 更新数据库
                    invationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_ACCEPT_APPLICATION);
//                        Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invationInfo);

                    // 更新内存
                    runOnUiThread(() -> {
                        Toast.makeText(FriendActivity.this, "接受申请", Toast.LENGTH_SHORT).show();

                        refresh();
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            });
        }

        // 拒绝申请按钮
        @Override
        public void onApplicationReject(final InvationInfo invationInfo) {
            ThreadHelper.getInstance().getExecutors().execute(() -> {
                try {
                    // 告诉环信服务器拒绝了申请
                    EMClient.getInstance().groupManager().declineApplication(invationInfo.getGroup().getGroupId(), invationInfo.getGroup().getInvatePerson(), "拒绝申请");

                    // 更新本地数据库
                    invationInfo.setStatus(InvationInfo.InvitationStatus.GROUP_REJECT_APPLICATION);
//                        Model.getInstance().getDbManager().getInviteTableDao().addInvitation(invationInfo);

                    // 更新内存
                    runOnUiThread(() -> {
                        Toast.makeText(FriendActivity.this, "拒绝申请", Toast.LENGTH_SHORT).show();

                        refresh();
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();

                    runOnUiThread(() -> Toast.makeText(FriendActivity.this, "拒绝申请失败", Toast.LENGTH_SHORT).show());
                }
            });
        }
    };
    private InviteAdapter inviteAdapter;
    private LocalBroadcastManager mLBM;
    private BroadcastReceiver InviteChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            // 刷新页面
            refresh();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_friend);
        initView();

        initData();
    }

    private void initData() {
        // 初始化listview
        inviteAdapter = new InviteAdapter(this, mOnInviteListener);

        lv_invite.setAdapter(inviteAdapter);

        // 刷新方法
        refresh();

        // 注册邀请信息变化的广播
        mLBM = LocalBroadcastManager.getInstance(this);
        mLBM.registerReceiver(InviteChangedReceiver, new IntentFilter(Constants.CONTACT_INVITE_CHANGED));
//        mLBM.registerReceiver(InviteChangedReceiver, new IntentFilter(Constants.GROUP_INVITE_CHANGED));
    }

    private void refresh() {
        // 获取数据库中的所有邀请信息
        UserInfo userInfo=new UserInfo("qwe123","qwe123");
        InvationInfo invationInfo=new InvationInfo(userInfo,null,"邀请你", InvationInfo.InvitationStatus.NEW_INVITE);
        UserInfo userInfo1=new UserInfo("qwer1234","qwer1234");
        InvationInfo invationInfo1=new InvationInfo(userInfo1,null,"邀请你", InvationInfo.InvitationStatus.NEW_INVITE);
        List<InvationInfo> invitations = new ArrayList<>();
        invitations.add(invationInfo);
        invitations.add(invationInfo1);

        // 刷新适配器
        inviteAdapter.refresh(invitations);
    }

    private void initView() {
        lv_invite = (ListView)findViewById(R.id.lv_invite);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mLBM.unregisterReceiver(InviteChangedReceiver);
    }
}
